package com.agd.quick.states;
//Gp
import java.util.Random;

import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.ITouchArea;
import org.andengine.input.touch.TouchEvent;
import org.andengine.util.color.Color;

import android.view.KeyEvent;
import lib.defines.GameEngineConfiguration;
import lib.elementgame.GameAnim;
import lib.elementgame.GameSprite;
import lib.elementgame.GameText;
import lib.elementgame.Mfx;
import lib.elementgame.Sfx;
import lib.engine.Anchor;
import lib.engine.GameEngine;
import lib.engine.GameState;

public class StateGamePlay extends GameState {
        private static final int LIVE_BAR_COUNT = 3;
        private static final int TURBO_BAR_COUNT = 5;
        private static final int TIWI_MAX_STATE = 6;
        private static final int TIWI_LARI = 0;
        private static final int TIWI_LOMPAT = 1;
        private static final int TIWI_HIT = 2;
        private static final int TIWI_LOSE1 = 3;
        private static final int TIWI_LOSE2 = 4;
        private static final int TIWI_AWAL = 5;
        private static int live_count;
        private int best;
        private int egg;
        private int gas;
        private int poop;
        private int ach10 = 1;
        private int ach9 = 1;
        private int blinkcount;
        private final float[] obstacle_y = { 198, 400 };
        private final float [] player_speed = {6, 6.8f, 7.6f, 8.4f, 9.2f, 10, 14};
        
        private static GameSprite[] background = new GameSprite[2];
        private static GameSprite[] background2 = new GameSprite[2];
        private static GameSprite[] background3 = new GameSprite[2];

        private static GameSprite btnPause;
        private static GameSprite turbo;
        
        private static GameSprite [] turbo2 = new GameSprite[TURBO_BAR_COUNT];
        private static GameSprite [] live_bar = new GameSprite[LIVE_BAR_COUNT];
        
        private Rectangle bg_game;

        
        private static GameSprite pBg;
        private static GameAnim pRetry;
        private static GameAnim pQuit;
        private static GameAnim pResume;

        private static GameSprite PLAYER;

        private static GameSprite lives_bg;

        private static GameAnim bensin;
        private static GameAnim telur;
        private static GameAnim pup;
        private static GameAnim busuk;
        private static GameSprite batu;
        private static GameSprite pagar;
        private static GameSprite sawah;
        
        private static GameAnim[] tiwi = new GameAnim[TIWI_MAX_STATE];

        private Rectangle hitam;
        Random rand = new Random();

        private int camCenterX = 0;
        private int camCenterY = 0;

        private float jalan = 0;
        private int meter = 0;
        private int jarak = 350;
        private int turbobar = 0;

        private boolean keluar;
        private boolean isHit = false;
        private boolean isGameOver1 = false;
        private boolean isGameOver2 = false;
        private boolean isJump = false;
        private boolean isJumped = false;
        private boolean isNos = false;
        private boolean afterNos = false;
        private boolean afterJump = false;
        private boolean awal = true;
        private boolean Setting_Vibration = true;
        private boolean Setting_Sound;
        
        
        private boolean useNos = false;
        private boolean useDamage = false;
        private float currentSpeed;
        private int speednormal;
        
        private int maxJump = 180;
        private int ground = 270;
        
        private GameSprite loser;
        private GameText[] Only_high = new GameText[3];
        private GameSprite medals_gold;
        private GameSprite medals_silver;
        private GameSprite medals_bronze;
        private GameText txtScore;
        private int score = 0;
        
        private String datScr;
        private int iniScore = 0;
        public StateGamePlay(GameEngine engine) {
                super(engine);
                // TODO Auto-generated constructor stub
        }

        @Override
        public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                        ITouchArea pTouchArea, float pTouchAreaLocalX,
                        float pTouchAreaLocalY) {
                // TODO Auto-generated method stub
                
                switch (pSceneTouchEvent.getAction()) {
                case TouchEvent.ACTION_DOWN:
                        if (pTouchArea == btnPause && btnPause.isVisible()) {
                                medals_gold.setVisible(!false);
                                medals_silver.setVisible(!false);
                                medals_bronze.setVisible(!false);
                                if(Setting_Vibration){
                                        engine.vibrate(200);
                                }
                                else{
                                        engine.vibrate(0);
                                }
                                
                                if (isPaused()) {
                                        resume();
                                } else {                                        
                                        pause();
                                }
                        }
                        if (pTouchArea == hitam && !(pTouchAreaLocalX >= btnPause.getX() && pTouchAreaLocalY <= btnPause.getY() + btnPause.getHeight()) && !hitam.isVisible() && !isHit && !isGameOver1 && !isGameOver2) {
                            if (isJump == false) {
                                    isJump = true;
                                    isJumped = false;
                            }
                        }
                        if (pTouchArea == pRetry && pRetry.isVisible()) {
                           pRetry.setCurrentTileIndex(1);
                        } else if (pTouchArea == pQuit && pQuit.isVisible()) {
                        	pQuit.setCurrentTileIndex(1);

                        } else if (pTouchArea == pResume && pResume.isVisible()) {
                        	pResume.setCurrentTileIndex(1);
                        }
                    break;
                case TouchEvent.ACTION_UP:
                        if (pTouchArea == pRetry && pRetry.isVisible()) {
                                if(Setting_Vibration){
                                        engine.vibrate(200);
                                }
                                else{
                                        engine.vibrate(0);
                                }
                                
                                reset();
                        } else if (pTouchArea == pQuit && pQuit.isVisible()) {
                                if(Setting_Vibration){
                                        engine.vibrate(200);
                                }
                                else{
                                        engine.vibrate(0);
                                }
                                
                                
                                exitState(MainMenuState);

                        } else if (pTouchArea == pResume && pResume.isVisible()) {
                                if(Setting_Vibration){
                                        engine.vibrate(200);
                                }
                                else{
                                        engine.vibrate(0);
                                }
                                
                                resume();
                        }
                        pResume.setCurrentTileIndex(0);
                        pRetry.setCurrentTileIndex(0);
                        pQuit.setCurrentTileIndex(0);
                        break;
                case TouchEvent.ACTION_MOVE:
                    if (pTouchArea == pRetry && pRetry.isVisible()) {
                        pRetry.setCurrentTileIndex(1);
                        pResume.setCurrentTileIndex(0);
                        pQuit.setCurrentTileIndex(0);
                     } else if (pTouchArea == pQuit && pQuit.isVisible()) {
                     	pQuit.setCurrentTileIndex(1);
                     	pRetry.setCurrentTileIndex(0);
                     	pResume.setCurrentTileIndex(0);
                     } else if (pTouchArea == pResume && pResume.isVisible()) {
                     	pResume.setCurrentTileIndex(1);
                     	pRetry.setCurrentTileIndex(0);
                     	pQuit.setCurrentTileIndex(0);
                     }
                }
                return false;
        }

        @Override
        public void initComponent() {
                // TODO Auto-generated method stub
        	
                for (int i = 0; i < background.length; i++) {
                        background[i] = new GameSprite(GP_SPRITE_BACKGGROUND, engine);
                }
                for (int i = 0; i < background.length; i++) {
                        background2[i] = new GameSprite(GP_SPRITE_BACKGGROUND2, engine);
                }
                for (int i = 0; i < background.length; i++) {
                        background3[i] = new GameSprite(GP_SPRITE_BACKGGROUND3, engine);
                }
                lives_bg = new GameSprite(GP_SPRITE_HEALTH_BG, engine);
                for (int i = 0; i < LIVE_BAR_COUNT; i++) {
                        live_bar[i] = new GameSprite(GP_SPRITE_HEALTH_1 + i, engine);
                }
                turbo = new GameSprite(GP_SPRITE_TURBO_BG,engine);
                for(int i = 0; i < TURBO_BAR_COUNT; i++){
                        turbo2[i] = new GameSprite(GP_SPRITE_TURBO_1 + i, engine);
                }
                hitam = new Rectangle(0, 0, 800, 480, engine.getVertexBufferObjectManager());
                btnPause = new GameSprite(GP_SPRITE_PAUSE, engine);
                pBg = new GameSprite(GP_SPRITE_PAUSE_BG, engine);
                pRetry = new GameAnim(GP_ANIM_P_RETRY, engine);
                pQuit = new GameAnim(GP_ANIM_P_QUIT, engine);
                pResume = new GameAnim(GP_ANIM_P_PLAY, engine);

                for (int i = 0; i < TIWI_MAX_STATE; i++) {
                        tiwi[i] = new GameAnim(GP_ANIM_TIWI_LARI + i, engine);
                }
                PLAYER = new GameSprite(GP_SPRITE_PLAYER, engine);
                
                        bensin = new GameAnim(GP_ANIM_ITEM_BENSIN, engine);
                        telur = new GameAnim(GP_ANIM_ITEM_TELUR, engine);
                        pup = new GameAnim(GP_ANIM_ITEM_POOP, engine);
                        busuk = new GameAnim(GP_ANIM_ITEM_BUSUK, engine);
                        batu = new GameSprite(GP_SPRITE_BATU, engine);
                        pagar = new GameSprite(GP_SPRITE_PAGAR, engine);
                        sawah = new GameSprite(GP_SPRITE_SAWAH, engine);
                
                Only_high[0] = new GameText("You Got 4th",100, engine.getFont(FONT_SCORE), engine);
                Only_high[1] = new GameText("You Got 5th",100, engine.getFont(FONT_SCORE), engine);
                Only_high[2] = new GameText("",100, engine.getFont(FONT_SCORE), engine);
                loser           = new GameSprite(GP_SPRITE_YOULOSE, engine);
                medals_gold = new GameSprite(MEDALS_GOLD, engine);
                medals_silver = new GameSprite(MEDALS_SILVER, engine);
                medals_bronze = new GameSprite(MEDALS_BRONZE, engine);
                
                txtScore = new GameText("", 30, engine.getFont(FONT_CIRCULAT_20_BLACK), engine);
                
                bg_game = new Rectangle(0, 0, 800, 480, engine.getVertexBufferObjectManager());
        }

        @Override
        protected void init() {
                // TODO Auto-generated method stub
                keluar = false;
                blinkcount = 0;
                afterJump = false;
                if(Integer.parseInt(engine.getDatabase().getData(SETTING_SOUND, 0, 1)) == 0){
                        Setting_Sound = false;
                }
                else{
                        Setting_Sound = true;
                }
                if(Setting_Sound){
                        Mfx.Pause(BG_SOUND);
                        Mfx.setVolume(SOUND_TRACTOR, 0);
                        Mfx.setVolume(SOUND_BG_GAMEPLAY, 0.7f);
                        Mfx.Play(SOUND_BG_GAMEPLAY);
                        Mfx.setVolume(SOUND_TRACTOR, 1);
                        Mfx.Play(SOUND_TRACTOR);
                        }
                hitam.setColor(Color.BLACK);
                hitam.setAlpha(0.5f);
                hitam.setVisible(false);
                camCenterX = GameEngineConfiguration.masterWidth / 2;
                camCenterY = GameEngineConfiguration.masterHeight / 2;
                        bensin.setPosition(0, 0);
                        telur.setPosition(0, 0);
                        pup.setPosition(0, 0);
                        busuk.setPosition(0, 0);
                        batu.setPosition(0, 0);
                        pagar.setPosition(0, 0);
                        sawah.setPosition(0, 0);
                        bensin.animate(400);
                        telur.animate(400);
                        pup.animate(400);
                        busuk.animate(400);
                
                if(Integer.parseInt(engine.getDatabase().getData(SETTING_VIBRATION, 0, 1)) == 0){
                        Setting_Vibration = false;
                }
                else{
                        Setting_Vibration = true;
                }
                egg = 0;
                gas = 0;
                poop = 0;
                best = 5;
                ach10 = 1;
                ach9 = 1;
                useNos = false;
                useDamage = false;
                engine.startWaktu();
                engine.resetWaktu();
                engine.resumeWaktu();
                meter = 0;
                live_count = LIVE_BAR_COUNT - 1;
                turbobar = -1;
                turbo.setAlpha(0.2f);
                for(int i = 0; i < TURBO_BAR_COUNT; i++){
                        turbo2[i].setVisible(!true);
                }
                speednormal = 0;
                awal = true;
                tiwi[TIWI_AWAL].animate(120, false);
                tiwi[TIWI_AWAL].setVisible(true);
                tiwi[TIWI_LARI].setVisible(false);
                tiwi[TIWI_LOMPAT].setVisible(false);
                tiwi[TIWI_HIT].setVisible(false);
                tiwi[TIWI_LOSE1].setVisible(false);
                tiwi[TIWI_LOSE2].setVisible(false);
                for (int i = 0; i < TIWI_MAX_STATE; i++) {
                        tiwi[i].setIgnoreUpdate(false);
                }
                PLAYER.setAlpha(0);
                pBg.setVisible(false);
                pQuit.setVisible(false);
                pRetry.setVisible(false);
                pResume.setVisible(false);
                medals_gold.setVisible(!false);
                medals_silver.setVisible(!false);
                medals_bronze.setVisible(!false);
                btnPause.setVisible(true);
                isHit = false;
                isGameOver1 = false;
                isGameOver2 = false;
                isJump = false;
                isJumped = false;
                isNos = false;
                afterNos = false;
                jalan = 0;
                jarak = 350;
                for (int i = 0; i < LIVE_BAR_COUNT; i++) {
                        live_bar[i].setVisible(true);
                }
                
                
                background[0].setWidth(800);
                background[0].setHeight(550);
                background[1].setWidth(800);
                background[1].setHeight(550);

                background2[0].setWidth(800);
                background2[0].setHeight(450);
                background2[1].setWidth(800);
                background2[1].setHeight(450);

                background3[0].setWidth(800);
                background3[0].setHeight(450);
                background3[1].setWidth(800);
                background3[1].setHeight(450);
                
//              engine.getDatabase().insertData(TABLE_SCORE, new String[]{"0", "10"});
//              String strScore = engine.getDatabase().getData(TABLE_SCORE, 0, 1);
                
                score = 0;
                txtScore.setText("Score = " + score);
                
                bg_game.setColor(Color.WHITE);
                bg_game.setAlpha(0.1f);
        }

        @Override
        protected void attach() {
                // TODO Auto-generated method stub
                for (int i = 0; i < background.length; i++) {
                        engine.scene.attachChild(background3[i]);

                }
                for (int i = 0; i < background.length; i++) {

                        engine.scene.attachChild(background2[i]);

                }
                for (int i = 0; i < background.length; i++) {

                        engine.scene.attachChild(background[i]);
                }
                engine.hud.attachChild(bg_game);
                engine.hud.attachChild(lives_bg);
                for (int i = 0; i < LIVE_BAR_COUNT; i++) {
                        engine.hud.attachChild(live_bar[i]);
                }
                engine.hud.attachChild(hitam);
                engine.hud.attachChild(turbo);
                for(int i = 0; i < TURBO_BAR_COUNT; i++){
                        engine.hud.attachChild(turbo2[i]);
                }
                        engine.scene.attachChild(bensin);
                        engine.scene.attachChild(telur);
                        engine.scene.attachChild(pup);
                        engine.scene.attachChild(busuk);
                        engine.scene.attachChild(batu);
                        engine.scene.attachChild(pagar);
                        engine.scene.attachChild(sawah);
                engine.scene.attachChild(PLAYER);
                for (int i = 0; i < TIWI_MAX_STATE; i++) {
                        PLAYER.attachChild(tiwi[i]);
                }
                engine.hud.attachChild(btnPause);
                engine.hud.attachChild(pBg);
                pBg.attachChild(pRetry);
                pBg.attachChild(pQuit);
                pBg.attachChild(pResume);
                pBg.attachChild(medals_gold);
                pBg.attachChild(medals_silver);
                pBg.attachChild(medals_bronze);
                pBg.attachChild(Only_high[0]);
                pBg.attachChild(Only_high[1]);
                pBg.attachChild(Only_high[2]);
                pBg.attachChild(loser);
                
                engine.hud.attachChild(txtScore);
        }

        @Override
        protected void detach() {
                // TODO Auto-generated method stub
                bg_game.detachSelf();
                for (int i = 0; i < background.length; i++) {
                        background3[i].detachSelf();

                }
                for (int i = 0; i < background.length; i++) {

                        background2[i].detachSelf();

                }
                for (int i = 0; i < background.length; i++) {

                        background[i].detachSelf();
                }
                lives_bg.detachSelf();
                for (int i = 0; i < LIVE_BAR_COUNT; i++) {
                        live_bar[i].detachSelf();
                }
                hitam.detachSelf();
                turbo.detachSelf();
                for(int i = 0; i<TURBO_BAR_COUNT; i++){
                        turbo2[i].detachSelf();
                }
                
                        bensin.detachSelf();
                        telur.detachSelf();
                        pup.detachSelf();
                        busuk.detachSelf();
                        batu.detachSelf();
                        pagar.detachSelf();
                        sawah.detachSelf();
                PLAYER.detachSelf();
                for (int i = 0; i < TIWI_MAX_STATE; i++) {
                        tiwi[i].detachSelf();
                }
                btnPause.detachSelf();
                pBg.detachSelf();
                medals_gold.detachSelf();
                medals_silver.detachSelf();
                medals_bronze.detachSelf();
                pRetry.detachSelf();
                pQuit.detachSelf();
                pResume.detachSelf();
                Only_high[0].detachSelf();
                Only_high[1].detachSelf();
                Only_high[2].detachSelf();
                loser.detachSelf();
                
                txtScore.detachSelf();
        }

        @Override
        protected void setPosition() {
                lives_bg.setPosition(Anchor.TOP_LEFT);
                for(int i =0; i< LIVE_BAR_COUNT; i++){
                        live_bar[i].setPosition(67 , 9, Anchor.TOP_LEFT);
                }
                turbo.setPosition(5, 0, Anchor.CENTER_LEFT);
                        turbo2[0].setPosition(10,320);
                        turbo2[1].setPosition(10, turbo2[0].getY()-turbo2[0].getHeight() + 1);
                        turbo2[2].setPosition(10, turbo2[1].getY() - turbo2[1].getHeight() + 8);
                        turbo2[3].setPosition(10, turbo2[2].getY() - turbo2[2].getHeight()-5);
                        turbo2[4].setPosition(10, turbo2[3].getY() - turbo2[3].getHeight());
                PLAYER.setPosition(200, ground);
                tiwi[TIWI_LARI].setPosition(-120, -20);
                tiwi[TIWI_LOMPAT].setPosition(-120, -40);
                tiwi[TIWI_HIT].setPosition(-90,-20);
                tiwi[TIWI_LOSE1].setPosition(-90, -30);
                tiwi[TIWI_LOSE2].setPosition(-90, -30);
                tiwi[TIWI_AWAL].setPosition(-90, -20);
                background[0].setX(0);
                background[0].setY(-70);
                background[1].setX(background[0].getWidth());
                background[1].setY(-70);

                background2[0].setX(0);
                background2[0].setY(-20);
                background2[1].setX(background2[0].getWidth());
                background2[1].setY(-20);

                background3[0].setX(0);
                background3[0].setY(-50);
                background3[1].setX(background3[0].getWidth());
                background3[1].setY(-50);

                btnPause.setPosition(Anchor.TOP_RIGHT);
                pBg.setPosition(Anchor.CENTER);
                pRetry.setPosition(-50, -40, Anchor.BOTTOM_RIGHT);
                pQuit.setPosition(50, -40, Anchor.BOTTOM_LEFT);
                pResume.setPosition(0, -20, Anchor.CENTER);
                medals_gold.setPosition(Anchor.CENTER);
                medals_silver.setPosition(Anchor.CENTER);
                medals_bronze.setPosition(Anchor.CENTER);
                
                Only_high[0].setPosition(0, 0, Anchor.CENTER);
                Only_high[1].setPosition(0, 0, Anchor.CENTER);
                loser.setPosition(0,0, Anchor.CENTER);
                txtScore.setPosition(150, 0, Anchor.TOP_CENTER);
        }

        @Override
        protected void registerTouch() {
                // TODO Auto-generated method stub
        	engine.hud.registerTouchArea(hitam);
                engine.hud.registerTouchArea(btnPause);
                engine.hud.registerTouchArea(pRetry);
                engine.hud.registerTouchArea(pQuit);
                engine.hud.registerTouchArea(pResume);
        }

        @Override
        protected void unregisterTouch() {
                // TODO Auto-generated method stub
        	engine.unregisterHudTouch(hitam);
                engine.unregisterHudTouch(btnPause);
                engine.unregisterHudTouch(pRetry);
                engine.unregisterHudTouch(pQuit);
                engine.unregisterHudTouch(pResume);
        }

        @Override
        protected void onUpdate() {
                // TODO Auto-generated method stub
                medals_gold.setVisible(!false);
                medals_silver.setVisible(!false);
                medals_bronze.setVisible(!false);
                
                if(awal && !tiwi[TIWI_AWAL].isAnimationRunning()){
                        tiwi[TIWI_AWAL].setVisible(false);
                        tiwi[TIWI_LARI].animate(120);
                        tiwi[TIWI_LARI].setVisible(true);
                        awal = false;
                }
                if(ach10 == 1){
                        if(score < 250 && useNos){
                                ach10 = 2;
                        }
                        else if(score >= 250){
                                ach10 = 3;
                        }
                }
                if(ach9 == 1){
                        if(score < 250 && useDamage){
                                ach9 = 2;
                        }
                        else if(score >= 250){
                                ach9 = 3;
                        }
                }
                if(speednormal < 5 && engine.getWaktu() >= 30){
                        engine.resetWaktu();
                        speednormal++;
                }
                if(isNos && engine.getNos()){
                        if(turbobar != 0){
                                engine.startNos();
                                turbo2[turbobar].setVisible(false);
                                turbobar--;
                        }
                        else{
                        		turbo2[turbobar].setVisible(false);
                        		turbobar--;
                                tiwi[TIWI_LARI].animate(120);
                                isNos = false;
                                afterNos = true;
                                Sfx.Pause(SOUND_NITROS);
                                        bensin.setAlpha(1);
                                        telur.setAlpha(1);
                                        pup.setAlpha(1);
                                        busuk.setAlpha(1);
                                        batu.setAlpha(1);
                                        pagar.setAlpha(1);
                                        sawah.setAlpha(1);
                        }
                }
                if(afterNos){
                        if(System.currentTimeMillis() %2 == 0){
                                bensin.setAlpha(0);
                                telur.setAlpha(0);
                                pup.setAlpha(0);
                                busuk.setAlpha(0);
                                batu.setAlpha(0);
                                pagar.setAlpha(0);
                                sawah.setAlpha(0);
                        }
                        else{
                                bensin.setAlpha(1);
                                telur.setAlpha(1);
                                pup.setAlpha(1);
                                busuk.setAlpha(1);
                                batu.setAlpha(1);
                                pagar.setAlpha(1);
                                sawah.setAlpha(1);
                        }
                        blinkcount++;
                        if(blinkcount >= 100){
                                afterNos = false;
                                blinkcount = 0;
                                bensin.setAlpha(1);
                                telur.setAlpha(1);
                                pup.setAlpha(1);
                                busuk.setAlpha(1);
                                batu.setAlpha(1);
                                pagar.setAlpha(1);
                                sawah.setAlpha(1);
                        }
                }
                if(afterJump && !tiwi[TIWI_LOMPAT].isAnimationRunning()){
                	if(!isGameOver1 && !isGameOver2){
                		tiwi[TIWI_LARI].setVisible(true);
                    	tiwi[TIWI_LOMPAT].setVisible(false);
                	}
                    afterJump = false;
                }
                float bg1_x = background[1].getX();
                float bg1_w = background[1].getWidth();
                txtScore.setText("Score = " + score);
                
                
                engine.camera.setCenter(PLAYER.getX() + camCenterX - 200, camCenterY);
                PLAYER.setX(PLAYER.getX() + currentSpeed);
                jalan = jalan + ((currentSpeed-1)/2);
                if (jalan >= jarak) {
                        createObstacle();

                        jarak = (rand.nextInt(4) * 50) + 200;
                        jalan = 0;
                }

                if(isNos){
                        meter+=5;
                }
                else{
                        meter+=1;
                }
                if(meter >= 50){
                        score+=1;
                        meter = 0;
                }
                background[0].setX(background[0].getX());
                background[1].setX(background[1].getX());
                background2[0].setX(background2[0].getX() + 2);
                background2[1].setX(background2[1].getX() + 2);
                background3[0].setX(background3[0].getX() + 2.5f);
                background3[1].setX(background3[1].getX() + 2.5f);

                if (background[0].getX() + background[0].getWidth() < engine.camera
                                .getCenterX() - camCenterX) {
                        background[0].setX(background[1].getX() + background[1].getWidth());

                }
                if (bg1_x + bg1_w < engine.camera.getCenterX() - camCenterX) {
                        background[1].setX(background[0].getX() + background[0].getWidth());
                }
                if (background2[0].getX() + background2[0].getWidth() < engine.camera
                                .getCenterX() - camCenterX) {
                        background2[0].setX(background2[1].getX()
                                        + background2[1].getWidth());

                }
                if (background2[1].getX() + background2[1].getWidth() < engine.camera
                                .getCenterX() - camCenterX) {
                        background2[1].setX(background2[0].getX()
                                        + background2[0].getWidth());
                }

                if (background3[0].getX() + background3[0].getWidth() < engine.camera
                                .getCenterX() - camCenterX) {
                        background3[0].setX(background3[1].getX()
                                        + background3[1].getWidth());

                }
                if (background3[1].getX() + background3[1].getWidth() < engine.camera
                                .getCenterX() - camCenterX) {
                        background3[1].setX(background3[0].getX()
                                        + background3[0].getWidth());
                }
                if (isJump) {
                        tiwi_jump();
                } 
                if(turbobar == 4 && !isHit){
                	if(!isNos){
                		isNos = true;
                		Sfx.Play(SOUND_NITROS);
                		if(live_count < 2){
                    	int temp = live_count + 1;
                            live_bar[temp].setVisible(true);
                            live_count++;
                		}
                		else{
                            score = (int)(score*11/10);
                		}
                		tiwi[TIWI_LARI].animate(40);
                		engine.startNos();
                		useNos = true;
                        bensin.setAlpha(0.5f);
                        telur.setAlpha(0.5f);
                        pup.setAlpha(0.5f);
                        busuk.setAlpha(0.5f);
                        batu.setAlpha(0.5f);
                        pagar.setAlpha(0.5f);
                        sawah.setAlpha(0.5f);
                        turbo.setAlpha(1);
                	}
                }
                else{
                        if(turbobar == -1){
                                turbo.setAlpha(0.5f);
                        }
                        else{
                                turbo.setAlpha(0.7f);
                        }
                }
                if(!isGameOver1 && !isGameOver2 && !isHit && !isNos && !afterNos){
                        check_collision();
                }
                if(isNos){
                        currentSpeed = player_speed[6];
                }
                else{
                        currentSpeed = player_speed[speednormal];
                }
                if(isHit){
                        if( !tiwi[TIWI_HIT].isAnimationRunning()){
                        tiwi[TIWI_LARI].setVisible(!false);
                        tiwi[TIWI_LOMPAT].setVisible(false);
                        tiwi[TIWI_HIT].setVisible(false);
                        isHit = false;
                        }
                        else{
                                tiwi[TIWI_LARI].setVisible(false);
                                tiwi[TIWI_LOMPAT].setVisible(false);
                                tiwi[TIWI_HIT].setVisible(!false);
                        }
                }
                if(isGameOver1){
                        tiwi[TIWI_LARI].setVisible(false);
                        tiwi[TIWI_LOMPAT].setVisible(false);
                        tiwi[TIWI_HIT].setVisible(false);
                        if(!tiwi[TIWI_LOSE1].isAnimationRunning()){
                                tiwi[TIWI_LOSE1].setVisible(false);
                                tiwi[TIWI_LOSE2].setVisible(true);
                                tiwi[TIWI_LOSE2].animate(160, false);
                                isGameOver2 = true;
                                isGameOver1 = false;
                        }
                }
                if(isGameOver2){
                        if(!tiwi[TIWI_LOSE2].isAnimationRunning()){
                                
                                Mfx.setVolume(SOUND_BG_GAMEPLAY, 0);
                                //cek new high score atau bukan
                                
                                
                                engine.getDatabase().updateData(TABLE_SCOREs, new int[]{1}, new String[]{"" + score}, "WHERE id_scores = 0");
                                String nowScore = engine.getDatabase().getData(TABLE_SCOREs, 0, 1);
                                iniScore = Integer.parseInt(nowScore);
                                CheckAchievement();
                                for(int i =0; i<5; i++){
                                        String highscr = engine.getDatabase().getData(i, 0, 1);
                                        int hiscr = Integer.parseInt(highscr);
                                        if(iniScore>hiscr){
                                                for(int j=4; j>i; j--){
                                                        int gscr = Integer.parseInt(engine.getDatabase().getData(j- 1, 0, 1));
                                                        switch(j){
                                                        case 4:
                                                                datScr = "WHERE id_score4 = 0";
                                                                break;
                                                        case 3:
                                                                datScr = "WHERE id_score3 = 0";
                                                                break;
                                                        case 2:
                                                                datScr = "WHERE id_score2 = 0";
                                                                break;
                                                        case 1:
                                                                datScr ="WHERE id_score1 = 0";
                                                                break;
                                                        }
                                                        
                                                        engine.getDatabase().updateData(j, new int[]{1}, new String[]{"" + gscr}, datScr);
                                                        
                                                }
                                                switch(i){
                                                case 4:
                                                        datScr = "WHERE id_score4 = 0";
                                                        break;
                                                case 3:
                                                        datScr = "WHERE id_score3 = 0";
                                                        break;
                                                case 2:
                                                        datScr = "WHERE id_score2 = 0";
                                                        break;
                                                case 1:
                                                        datScr = "WHERE id_score1 = 0";
                                                        break;
                                                case 0:
                                                        datScr = "WHERE id_score0 = 0";
                                                }
                                                engine.getDatabase().updateData(i, new int[]{1}, new String[]{"" + iniScore}, datScr);
                                                best = i;
                                                break;
                                        }
                                }
                                if(best >= 4){
                                        Sfx.Play(SOUND_HIGHSCORE);
                                }
                                else {
                                        Sfx.Play(SOUND_NO_HIGHSCORE);
                                }
                                pause();
                                pResume.setVisible(false);
                                if(best == 0){
                                        medals_gold.setPosition(0, -30, Anchor.CENTER);
                                        medals_gold.setVisible(!false);
                                        medals_silver.setVisible(false);
                                        medals_bronze.setVisible(false);
                                        Only_high[0].setVisible(false);
                                        Only_high[1].setVisible(false);
                                        loser.setVisible(false);
                                        Only_high[2].setVisible(true);
                                        Only_high[2].setText("" + "New HighScore\n" + "Congratulation !" + "");
                                        Only_high[2].setPosition(0, 55, Anchor.CENTER);
                                }
                                else if(best == 1){
                                        medals_silver.setPosition(0, -30, Anchor.CENTER);
                                        medals_gold.setVisible(false);
                                        medals_silver.setVisible(!false);
                                        medals_bronze.setVisible(false);
                                        Only_high[0].setVisible(false);
                                        Only_high[1].setVisible(false);
                                        loser.setVisible(false);
                                        Only_high[2].setVisible(true);
                                        Only_high[2].setText("" + "Congratulation !\n" + " You Got Silver" + "");
                                        Only_high[2].setPosition(0, 55, Anchor.CENTER);
                                }
                                else if(best == 2){
                                        medals_bronze.setPosition(0, -30, Anchor.CENTER);
                                        medals_gold.setVisible(false);
                                        medals_silver.setVisible(false);
                                        medals_bronze.setVisible(!false);
                                        Only_high[0].setVisible(false);
                                        Only_high[1].setVisible(false);
                                        loser.setVisible(false);
                                        Only_high[2].setVisible(true);
                                        Only_high[2].setText("" + "Congratulation !\n" + "You Got Bronze" + "");
                                        Only_high[2].setPosition(0, 55, Anchor.CENTER);
                                }
                                else{
                                        medals_gold.setVisible(false);
                                        medals_silver.setVisible(false);
                                        medals_bronze.setVisible(false);
                                        if(best == 3){
                                                Only_high[0].setVisible(!false);
                                                Only_high[1].setVisible(false);
                                                Only_high[2].setVisible(false);
                                                loser.setVisible(false);
                                        }
                                        else if(best == 4){
                                                Only_high[1].setVisible(!false);
                                                Only_high[0].setVisible(false);
                                                Only_high[2].setVisible(false);
                                                loser.setVisible(false);
                                        }
                                        else{
                                                Only_high[1].setVisible(false);
                                                Only_high[0].setVisible(false);
                                                Only_high[2].setVisible(false);
                                                loser.setVisible(!false);
                                                }
                                }
                                
                                txtScore.setPosition(0, -100, Anchor.CENTER);
                        }
                }
                
        }

        private void CheckAchievement() {
                // TODO Auto-generated method stub
                
                if (Integer.parseInt(engine.getDatabase().getData(ACHIEVEMENT_1, 0, 1)) == 0){
                        if (score>= 100){
                                engine.getDatabase().updateData(ACHIEVEMENT_1, new int[]{1}, new String[]{"" + 1}, "WHERE id_ACH1 = 0");
                        }
                }
                if (Integer.parseInt(engine.getDatabase().getData(ACHIEVEMENT_2, 0, 1)) == 0){
                        if (score>= 500){
                                engine.getDatabase().updateData(ACHIEVEMENT_2, new int[]{1}, new String[]{"" + 1}, "WHERE id_ACH2 = 0");
                        }
                }
                if (Integer.parseInt(engine.getDatabase().getData(ACHIEVEMENT_3, 0, 1)) == 0){
                        if (score>= 1000){
                                engine.getDatabase().updateData(ACHIEVEMENT_3, new int[]{1}, new String[]{"" + 1}, "WHERE id_ACH3 = 0");
                        }
                }
                if (Integer.parseInt(engine.getDatabase().getData(ACHIEVEMENT_4, 0, 1)) == 0){
                        if (score>= 1500){
                                engine.getDatabase().updateData(ACHIEVEMENT_4, new int[]{1}, new String[]{"" + 1}, "WHERE id_ACH4 = 0");
                        }
                }
                if (Integer.parseInt(engine.getDatabase().getData(ACHIEVEMENT_5, 0, 1)) == 0){
                        if (score>= 2500){
                                engine.getDatabase().updateData(ACHIEVEMENT_5, new int[]{1}, new String[]{"" + 1}, "WHERE id_ACH5 = 0");
                        }
                }
                if (Integer.parseInt(engine.getDatabase().getData(ACHIEVEMENT_6, 0, 1)) == 0){
                        if (egg>= 25){
                                engine.getDatabase().updateData(ACHIEVEMENT_6, new int[]{1}, new String[]{"" + 1}, "WHERE id_ACH6 = 0");
                        }
                }
                if (Integer.parseInt(engine.getDatabase().getData(ACHIEVEMENT_7, 0, 1)) == 0){
                        if (gas>= 25){
                                engine.getDatabase().updateData(ACHIEVEMENT_7, new int[]{1}, new String[]{"" + 1}, "WHERE id_ACH7 = 0");
                        }
                }
                if (Integer.parseInt(engine.getDatabase().getData(ACHIEVEMENT_8, 0, 1)) == 0){
                        if (poop>= 25){
                                engine.getDatabase().updateData(ACHIEVEMENT_8, new int[]{1}, new String[]{"" + 1}, "WHERE id_ACH8 = 0");
                        }
                }
                if (Integer.parseInt(engine.getDatabase().getData(ACHIEVEMENT_10, 0, 1)) == 0){
                        if (ach10 == 3){
                                engine.getDatabase().updateData(ACHIEVEMENT_10, new int[]{1}, new String[]{"" + 1}, "WHERE id_ACH10 = 0");
                        }
                }
                if (Integer.parseInt(engine.getDatabase().getData(ACHIEVEMENT_9, 0, 1)) == 0){
                        if (ach9 == 3){
                                engine.getDatabase().updateData(ACHIEVEMENT_9, new int[]{1}, new String[]{"" + 1}, "WHERE id_ACH9 = 0");
                        }
                }
        }

        private void check_collision() {
                // TODO Auto-generated method stub
                        if (PLAYER.collidesWith(busuk) && busuk.isVisible()) {
                                Sfx.Play(SOUND_GET_TELUR_OBS);
                                busuk.setVisible(false);
                                score = (int) (score *4/5);
                                if(turbobar >= 0){
                                        turbo2[turbobar].setVisible(false);
                                        turbobar--;
                                }
                                else {
                                        if(live_count <= 0){
                                                gameover();
                                        }
                                        
                                        live_bar[live_count].setVisible(false);
                                		live_count--;
                                }
                        } else if (PLAYER.collidesWith(telur) && telur.isVisible()) {
                                Sfx.Play(SOUND_GET_TELUR_ITEM);
                                telur.setVisible(false);
                                egg++;
                                score += 5;
                        } else if(PLAYER.collidesWith(pup) && pup.isVisible()){
                                Sfx.Play(SOUND_GET_TELUR_OBS);
                                pup.setVisible(false);
                                poop++;
                                if(turbobar >= 0){
                                        turbo2[turbobar].setVisible(false);
                                        turbobar--;
                                }
                                else {
                                        if(live_count <= 0){
                                                gameover();
                                        }
                                        live_bar[live_count].setVisible(false);
                                		live_count--;
                                }
                        } else if(PLAYER.collidesWith(bensin) && bensin.isVisible()){
                                Sfx.Play(SOUND_GET_BENSIN);
                                bensin.setVisible(false);
                                gas++;
                                turbobar++;
                                turbo2[turbobar].setVisible(true);
                        } else if(PLAYER.collidesWith(batu) && batu.isVisible()){
//                                batu.setVisible(false);
                                
                                if(live_count <= 0){
                                        gameover();
                                }
                                else{
                                hit_obstacle();
                                }
                                
                                live_bar[live_count].setVisible(false);
                        		live_count--;
                        }
                        else if(PLAYER.collidesWith(pagar) && pagar.isVisible()){
//                                pagar.setVisible(false);
                                
                                if(live_count <= 0){
                                        gameover();
                                }
                                else{
                                        hit_obstacle();
                                }
                                live_bar[live_count].setVisible(false);
                        		live_count--;
                        }
                        else if(PLAYER.collidesWith(sawah) && sawah.isVisible()){
                                sawah.setVisible(false);
                                
                                if(live_count <= 0){
                                        gameover();
                                }
                                else{                                   
                                        hit_obstacle();
                                }
                                live_bar[live_count].setVisible(false);
                        		live_count--;
                        }
        }

        private void gameover() {
                // TODO Auto-generated method stub
                Sfx.Play(SOUND_GET_PAGAR_PATUNG);
                if(Setting_Vibration){
                        engine.vibrate(600);
                }
                else {
                        engine.vibrate(0);
                }
                
                isGameOver1 = true;
                btnPause.setVisible(false);
                tiwi[TIWI_LARI].setVisible(false);
                tiwi[TIWI_LOMPAT].setVisible(false);
                tiwi[TIWI_HIT].setVisible(false);
                tiwi[TIWI_LOSE2].setVisible(false);
                tiwi[TIWI_LOSE1].setVisible(true);
                tiwi[TIWI_LOSE1].animate(160, false);
        }

        private void hit_obstacle() {
                // TODO Auto-generated method stub
                Sfx.Play(SOUND_GET_PAGAR_PATUNG);
                
                if(Setting_Vibration){
                        engine.vibrate(450);
                }
                else {
                        engine.vibrate(0);
                }
                
                        useDamage = true;
                        isHit = true;
                        tiwi[TIWI_LARI].setVisible(false);
                        tiwi[TIWI_LOMPAT].setVisible(false);
                        tiwi[TIWI_HIT].setVisible(!false);
                        tiwi[TIWI_HIT].animate(160, false);             
        }

        private void tiwi_jump() {
                // TODO Auto-generated method stub
                if (isJumped == false) {
                        if(PLAYER.getY() - 3.5f > maxJump){
                                PLAYER.setY(PLAYER.getY() - 3.5f);
                        }
                        else{
                                PLAYER.setY(maxJump);
                                isJumped = true;
                        }
                        
                        tiwi[TIWI_AWAL].setVisible(false);
                        tiwi[TIWI_LARI].setVisible(false);
                        tiwi[TIWI_HIT].setVisible(false);
                        tiwi[TIWI_LOMPAT].setVisible(true);
                        if(!tiwi[TIWI_LOMPAT].isAnimationRunning()){
                                tiwi[TIWI_LOMPAT].animate(100, false);
                        }
                }

                if (isJumped == true) {
                        if(PLAYER.getY() + 4 < ground){
                                PLAYER.setY(PLAYER.getY() + 4);
                        }
                        else{
                                PLAYER.setY(ground);

                                if(!isGameOver2){
                                		afterJump = true;
                                        isJump = false;
                                }
                        }
                }

        }

        private void createObstacle() {
                // TODO Auto-generated method stub
                int a = rand.nextInt(16);
                int b = rand.nextInt(2);
                switch (a) {
                case 0:
                case 1:
                        if (pup.getX() < engine.camera.getXMin()) {
                                pup.setPosition(engine.camera.getXMax(), obstacle_y[b] - pup.getHeight());
                                pup.setVisible(true);
                        } else {
                                createObstacle();
                        }
                        break;
                case 2:
                case 3:
                        if (bensin.getX() < engine.camera.getXMin()) {
                                bensin.setPosition(engine.camera.getXMax(), obstacle_y[b] - bensin.getHeight());
                                bensin.setVisible(true);
                        } else {
                                createObstacle();
                        }
                        break;
                case 4:
                case 5:
                case 6:
                        if (telur.getX() < engine.camera.getXMin()) {
                                telur.setPosition(engine.camera.getXMax(), obstacle_y[b] - telur.getHeight());
                                telur.setVisible(true);
                        } else {
                                createObstacle();
                        }
                        break;
                case 7:
                case 8:
                        if (busuk.getX() < engine.camera.getXMin()) {
                                busuk.setPosition(engine.camera.getXMax(), obstacle_y[b] - busuk.getHeight());
                                busuk.setVisible(true);
                        } else {
                                createObstacle();
                        }
                        break;
                case 9:
                case 10:
                        if (batu.getX() < engine.camera.getXMin()) {
                                batu.setPosition(engine.camera.getXMax(), obstacle_y[1] - batu.getHeight());
                                batu.setVisible(true);
                        } else {
                                createObstacle();
                        }
                        break;
                case 11:
                case 12:
                        if (pagar.getX() < engine.camera.getXMin()) {
                                pagar.setPosition(engine.camera.getXMax(), obstacle_y[1] - pagar.getHeight());
                                pagar.setVisible(true);
                        } else {
                                createObstacle();
                        }
                        break;
                case 13:
                case 14:
                        if (sawah.getX() < engine.camera.getXMin()) {
                                sawah.setPosition(engine.camera.getXMax(), obstacle_y[1] - sawah.getHeight());
                                sawah.setVisible(true);
                        } else {
                                createObstacle();
                        }
                        break;
                }
        }

        @Override
        protected void onPaused() {
                // TODO Auto-generated method stub
                if(isNos == true){
                Sfx.Pause(SOUND_NITROS);
                }
                if(keluar){
                        exitState(MainMenuState);
                }
                hitam.setVisible(true);
                Mfx.Pause(SOUND_BG_GAMEPLAY);
                Mfx.Pause(SOUND_TRACTOR);
                pBg.setVisible(true);
                pQuit.setVisible(true);
                pRetry.setVisible(true);
                pResume.setVisible(true);
                medals_gold.setVisible(false);
                medals_silver.setVisible(false);
                medals_bronze.setVisible(false);
                Only_high[0].setVisible(false);
                Only_high[1].setVisible(false);
                Only_high[2].setVisible(false);
                loser.setVisible(false);
                engine.pauseWaktu();
                for (int i = 0; i < TIWI_MAX_STATE; i++) {
                        tiwi[i].setIgnoreUpdate(true);
                }
        }

        @Override
        protected void onResumed() {
                // TODO Auto-generated method stub
                hitam.setVisible(false);
                if(isNos == true){
                        if(Sfx.isBerhenti(SOUND_NITROS)){
                        Sfx.Resume(SOUND_NITROS);
                        }
                }

                if(Setting_Sound){
                        Mfx.Pause(BG_SOUND);
                        Mfx.setVolume(SOUND_TRACTOR, 0);
                        Mfx.setVolume(SOUND_BG_GAMEPLAY, 0.7f);
                        Mfx.Play(SOUND_BG_GAMEPLAY);
                        Mfx.setVolume(SOUND_TRACTOR, 1);
                        Mfx.Play(SOUND_TRACTOR);
                        }
                pBg.setVisible(false);
                pQuit.setVisible(false);
                pRetry.setVisible(false);
                medals_gold.setVisible(false);
                medals_silver.setVisible(false);
                medals_bronze.setVisible(false);
                Only_high[0].setVisible(false);
                Only_high[1].setVisible(false);
                Only_high[2].setVisible(false);
                loser.setVisible(false);
                pResume.setVisible(!true);
                engine.resumeWaktu();
                for (int i = 0; i < TIWI_MAX_STATE; i++) {
                        tiwi[i].setIgnoreUpdate(false);
                }
        }

        @Override
        public void onKeyUp(int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                        if (isPaused()) {
                                if(btnPause.isVisible()){
                                        resume();
                                }
                                else{
                                        keluar = true;
                                }
                        } else {
                                pause();
                        }
                }
                
        }

        @Override
        public void initLoading() {
                // TODO Auto-generated method stub
                
        }

}